package com.example.hrmsaas.system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.hrmsaas.company.entity.Department;
import com.example.hrmsaas.company.service.IDepartmentService;
import com.example.hrmsaas.system.entity.*;
import com.example.hrmsaas.system.mapper.PermissionMapper;
import com.example.hrmsaas.system.mapper.RolePermissionMapper;
import com.example.hrmsaas.system.mapper.UserMapper;
import com.example.hrmsaas.system.mapper.UserRoleMapper;
import com.example.hrmsaas.system.service.IRoleService;
import com.example.hrmsaas.system.service.IUserService;
import com.example.hrmsaas.system.utils.DataGridView;
import com.example.hrmsaas.system.utils.DateToTime;
import com.example.hrmsaas.system.utils.IdWorker;
import com.example.hrmsaas.system.utils.vo.UserVo;
import com.sun.org.apache.regexp.internal.RE;
import org.apache.commons.lang3.StringUtils;
import org.apache.juli.logging.Log;
import org.apache.juli.logging.LogFactory;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author 雷哥
 * @since 2021-07-01
 */
@Service
@Transactional

/**当前本类实现的Service对象不能懒加载，也不能用this,用了以后用户的aop切面不会生效，要实现aop切面，所以需要用ApplicationContextAware的上下文去ioc里面取出容器.
 通过上下文的方式将容器取出，把当前本类实现的Service变成一个代理对象
 */
public class UserServiceImpl<RoleMapper> extends ServiceImpl<UserMapper, User> implements IUserService, ApplicationContextAware {

    private Log log = (Log) LogFactory.getLog(UserServiceImpl.class);

    @Autowired
    private UserMapper userMapper;

    @Autowired
    UserRoleMapper userRoleMapper;

    @Autowired
    IRoleService roleService;

    @Autowired
    RolePermissionMapper rolePermissionMapper;

    @Autowired
    PermissionMapper permissionMapper;

    @Autowired
    @Lazy
    private IDepartmentService deptService;

    @Override
    public User getUserObjectByUserName(String username) {
        UserMapper userMapper = this.getBaseMapper();
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();

        if (null == username) {
          log.error("用户名不能为空");
          throw new RuntimeException("用户名不能为空");
        }else{
            queryWrapper.eq("username",username);
            User userObject =  userMapper.selectOne(queryWrapper);
            return userObject;
        }
    }

    @Override
    public DataGridView getUserList(UserVo userVo) {
        QueryWrapper<User> userQueryWrapper = new QueryWrapper<User>();
        if(null != userVo){
            if(null != userVo.getCompanyId()){
                userQueryWrapper.eq("company_id",userVo.getCompanyId());
            }
            if(null != userVo.getDeptId()){
                userQueryWrapper.in("deptid",userVo.getDeptId());
            }

            if(null != userVo.getHasDepartment()){
                    if(userVo.getHasDepartment()>0){
                        userQueryWrapper.isNotNull("deptid");
                    }else{
                        userQueryWrapper.isNull("deptid");
                    }
            }
            userQueryWrapper.like(StringUtils.isNotBlank(userVo.getAddress()),"address",userVo.getAddress());
            userQueryWrapper.like(StringUtils.isNotBlank(userVo.getName()),"name",userVo.getName()).or().like(StringUtils.isNotBlank(userVo.getName()),"loginname",userVo.getName());
        }
        userQueryWrapper.orderByDesc("create_time");
        Page<User> page = new Page<User>(userVo.getPage(),userVo.getLimit());
        userMapper.selectPage(page,userQueryWrapper);
        List<User> list = page.getRecords();
        for(User user:list){
            String deptId = user.getDeptid();
            String bossId = user.getMgr()==null?"0":user.getMgr();
            //根据ID去查询部门
            Department department = deptService.getById(deptId);
            user.setDepartmentName(department.getName());
            if(!bossId.equals("0")){
                IUserService userService = (IUserService)content.getBean(IUserService.class);
                User user2 =userService.getById(bossId);
                user.setBossName(user2.getName());
            }else{
                user.setBossName("无上级");
            }

        }

        return  new DataGridView(page.getTotal(),list);
    }

    @Override
    public boolean addUser(User user) {
        IdWorker idWorker = new IdWorker();
        String id = idWorker.nextId()+"";
        user.setId(id);
        user.setPwd("123456");
        user.setEnableState(1);
        user.setCreateTime(DateToTime.timestamToDatetime(System.currentTimeMillis()));//设置创建时间
        if( this.baseMapper.insert(user)>0){
            return true;
        }else{
            return false;
        }

    }

    @Override
    public User getUserByUid(String uid) {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("id",uid);
        QueryWrapper<UserRole> q2 = new QueryWrapper<>();
        q2.eq("user_id",uid);
        User user = this.baseMapper.selectOne(queryWrapper);
        List<UserRole> userRole = userRoleMapper.selectList(q2);
        System.out.print(userRole);
        Set<String> rolesIds = new HashSet<String>();
        for(UserRole ur:userRole){
            String roleId = ur.getRoleId();
            Role roleData = roleService.getById(roleId);
            rolesIds.add(roleData.getId());
        }
        user.setRoleIds(rolesIds);
        return  user;
    }

    @Override
    public boolean updateUser(User user) {
        User olduserData = this.getUserByUid(user.getId());
        System.out.print(olduserData.toString());
        olduserData.setUsername(user.getUsername());
        olduserData.setPwd(user.getPwd());
        olduserData.setDeptid(user.getDeptid());
        olduserData.setDepartmentName(user.getDepartmentName());
        if( this.baseMapper.updateById(olduserData)>0){
            return true;
        }else{
            return false;
        }

    }

    @Override
    public boolean delUserById(String id) {
        if(this.baseMapper.deleteById(id)>0){
            return true;
        }else{
            return false;
        }
    }


    @Override
    public List<User> getUserAllList(UserVo userVo) {
        return null;
    }

    @Override
    public boolean setRole(String userId, List<String> roleIds) {
        //1.获取用户实体
        User user = userMapper.selectById(userId);
        //2.构建角色列表
        Set<Role> roles = new HashSet<>();
        for(String roleId :roleIds){
           Role role = roleService.getById(roleId);
            roles.add(role);
        }
        QueryWrapper<UserRole> models = new QueryWrapper<UserRole>();
        if(null != roles) {
            //先删除原有的权限
            models.eq("user_id", userId);
            userRoleMapper.delete(models);
        }
            for(Role role:roles){
                String uid = userId;
                String role_id = role.getId();
                UserRole userRole = new UserRole();
                //保存权限是看看是否存在已有的权限
                models.eq("user_id",uid);
                models.eq("role_id",role_id);
                //如果存在先删除原有的权限
                    userRole.setRoleId(role_id);
                    userRole.setUserId(uid);
                    userRoleMapper.insert(userRole);
            }
            return true;
    }

    @Override
    public Set<Role> getRolesByUid(String id) {
        QueryWrapper<UserRole> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id",id);
        //获取用户的角色设置
        List<UserRole> list = userRoleMapper.selectList(queryWrapper);
        QueryWrapper<RolePermission> proWp = new QueryWrapper<>();
        Set<String> map = new HashSet<>();
        //取出用户所有的角色id
        for(UserRole userRole:list){
            map.add(userRole.getRoleId());
        }
        Set<Role> roles = new HashSet<>();
        Set<String> ids = new HashSet<>();
        //遍历所有角色id
        for(String role_id:map){
            Role role = roleService.getById(role_id);
            ids.add(role_id);
            roles.add(role);
        }
        //获取所有角色对应的权限
        proWp.in("role_id",ids);
        List<RolePermission> Datas = rolePermissionMapper.selectList(proWp);
        Set<Permission> permSet = new HashSet<>();
        for(RolePermission val:Datas){
            Permission permission = permissionMapper.selectById(val.getPermissionId());
            permSet.add(permission);
            for(String role_id:map){
                if(role_id.equals(val.getRoleId())){
                    for(Role role:roles){
                        role.setPermissions(permSet);
                    }
                }
            }
        }

        return  roles;
    }


    private ApplicationContext content;
    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {

    }
}
